package com.ziytek.web.citizen.configuration.db;

import com.ziytek.web.citizen.constant.DdsConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.util.Objects;

/**
 * @author fenghx
 * @version 1.0
 * @className DynamicDatasourceHolder
 * Description:
 * @date 2024/3/12 9:27
 */
@Slf4j
@RefreshScope
public class DynamicDatasourceHolder {

    private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();

    public static void setDataSource(String type) {
        try {
            HOLDER.set(type);
        } catch (Exception e) {
            log.error("setDataSource error:", e);
        }
    }

    public static String getDataSource() {
        try {
            var dataSourceName = HOLDER.get();
            return Objects.isNull(dataSourceName) ? DdsConstant.DS_MASTER : dataSourceName;
        } catch (Exception e) {
            log.error("getDataSource error:", e);
        }
        return null;
    }

    public static void removeDataSource() {
        try {
            HOLDER.remove();
        } catch (Exception e) {
            log.error("removeDataSource error:", e);
        }
    }
}
